import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { LoginService } from '../../login/common-service/login.service';
import { map, catchError } from 'rxjs/operators';
import { AppSettings } from '../config/app-settings';

@Injectable()
export class AgentAuthGuard implements CanActivate {
    constructor(private router: Router, private loginService: LoginService) { }

    // canActivate() {
    //     if (localStorage.getItem('isLoggedin')) {
    //         return true;
    //     }

    //     this.router.navigate(['/login']);
    //     return false;
    // }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
        if (AppSettings.mode === 'web') {
            console.log("mock auth");
            if (localStorage.getItem('isLoggedin')) {
                return true;
            }
            this.router.navigate(['/login']);
            return false;
        } else {
            console.log("auth from server");
            return this.loginService.isAuthenticated(["agent"]).pipe(
                map(e => {
                    if (e) {
                        return true;
                    }
                    this.router.navigate(['/login']);
                    return false;
                }),
                catchError((err) => { 
                    console.log("no login so redirect");
                    this.router.navigate(['/login']);
                    return throwError(err); 
                })
            );
        }

    }
}
